from odoo import fields, models, api


class WorkStation(models.Model):
    _name = 'work.station'
    _description = 'Work Station'
    _order = 'sequence'
    _sql_constraints = [
        ("name_uniq", "unique (name)", "That name already exists !"),
    ]

    name = fields.Char(string="Work Station Name", required=True, copy=False)
    code = fields.Char(string="Work station Code", required=True, copy=False)
    name_eng = fields.Char(string="Name_ENG")
    name_thai = fields.Char(string="Name_thai")
    sequence = fields.Integer(string='Sequence')
    display_name = fields.Char(compute='_compute_display_name', string='Display Name')
    center_ids = fields.One2many('mrp.workcenter', 'work_station_id')
    scrap_reason_ids = fields.Many2many('scrap.reason', 's_work_station_scrap_reason_rel', string='scrap reason')
    active = fields.Boolean(default=True)

    timeout_count = fields.Integer('Timeout Count', compute='_compute_timeout_count')
    target_daily_production = fields.Integer('Target daily production', default=0)
    target_wip = fields.Integer('Target PNL', default=0)

    minimum_output = fields.Integer(string='Minimum output (PNL)')
    maximum_output = fields.Integer(string='Maximum output (PNL)')

    hour_output = fields.Integer(string='Hour output', compute='_compute_hour_output', store=True)

    disuse = fields.Boolean(string='Disuse', default=False, copy=False)

    user_ids = fields.Many2many('res.users', 's_work_station_res_users_rel', string='Users')

    @api.depends('minimum_output')
    def _compute_hour_output(self):
        for rec in self:
            if not rec.minimum_output:
                continue
            rec.hour_output = int(round(rec.minimum_output / 24))

    def _compute_timeout_count(self):
        work_order_ids = self.env['mrp.workorder'].search([('state', 'in', ('ready', 'progress'))])
        work_order_ids = work_order_ids.filtered(lambda x: x.s_stop_time > 24)
        station_count_vals = {}
        for wo in work_order_ids:
            if wo.work_station_id.id in station_count_vals:
                station_count_vals[wo.work_station_id.id] += 1
            else:
                station_count_vals.setdefault(wo.work_station_id.id, 1)

        # 设置每个工作中心的超时工单数量
        for rec in self:
            rec.timeout_count = station_count_vals.get(rec.id, 0)

    @api.depends('name', 'code')
    def _compute_display_name(self):
        for rec in self:
            if rec.code and rec.name:
                rec.display_name = f'{rec.code}【{rec.name}】'
            else:
                rec.display_name = rec.name

    def action_workcenter(self):
        action = self.env["ir.actions.actions"]._for_xml_id("mrp.mrp_workorder_todo")
        action['domain'] = [('work_station_id', '=', self.id), ('state', 'in', ('ready', 'progress'))]
        return action

    def get_action_workorder_tree_timeout(self):
        action = self.env["ir.actions.actions"]._for_xml_id("mrp.mrp_workorder_todo")
        work_order_ids = self.env['mrp.workorder'].search([('state', 'in', ('ready', 'progress')), ('workcenter_id.work_station_id', '=', self.id)])
        work_order_ids = work_order_ids.filtered(lambda x:  x.s_stop_time > 24)
        action['domain'] = [('id', 'in', work_order_ids.ids)]
        return action
